<template>
  <div>
    <el-upload action="http://up-z2.qiniup.com" :data="dataObj" :list-type="listType" :file-list="fileList"
      :before-upload="beforeUpload" :on-remove="handleRemove" :on-success="handleUploadSuccess"
      :on-preview="handlePreview" :limit="maxCount" :on-exceed="handleExceed" :show-file-list="showFile">
      <i class="el-icon-plus"></i>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt />
    </el-dialog>
  </div>
</template>
<script>
  import { policy } from "./policy";
  import { getUUID } from '@/utils'
  import * as qiniu from "qiniu-js";


  export default {
    name: "multiUpload",
    props: {
      //图片属性数组
      value: Array,
      //最大上传图片数量
      maxCount: {
        type: Number,
        default: 30
      },
      listType: {
        type: String,
        default: "picture-card"
      },
      showFile: {
        type: Boolean,
        default: true
      }

    },
    data() {
      return {
        dataObj: {
          // policy: "",
          // signature: "",
          // key: "",
          // ossaccessKeyId: "",
          // dir: "",
          // host: "",
          // uuid: ""
          token: '',
          url: '',
          dirPrefix: '',
          timePrefix: ''
        },
        dialogVisible: false,
        dialogImageUrl: null,
        url: ''
      };
    },
    computed: {
      fileList() {
        let fileList = [];
        for (let i = 0; i < this.value.length; i++) {
          fileList.push({ url: this.value[i] });
        }

        return fileList;
      }
    },
    mounted() { },
    methods: {
      qiniuUp(file, _self) {
        console.log("qiniu上传", _self.dataObj);
        // 七牛token
        var qiniuToken = _self.dataObj.token
        var fileName = file.name;
        // 获取文件后缀名 .jpg
        var suffix = fileName.substring(fileName.lastIndexOf("."), fileName.length)
        // console.log("文件信息：",fileName,suffix)
        // 获取文件大小 单位KB
        var size = (file.size / 1024).toFixed(2)
        // console.log("文件信息：",fileName,suffix,size)

        // 设置上传的七牛key 上传成功需要把这个值提交到后台
        var bucketToken = _self.dataObj.dirPrefix + '/' + _self.dataObj.timePrefix + getUUID() + suffix
        this.fileName = bucketToken
        // console.log("文件信息2：", fileName, suffix, size, bucketToken)
        this.url = _self.dataObj.url + '/' + bucketToken
        console.log("url", this.url)
        // console.log("骑牛信息", file, bucketToken, qiniuToken, putExtra, config)

        console.log("bucketToken 地址", bucketToken)
        // 实例化七牛云的上传实例
        var observable = qiniu.upload(file, bucketToken, qiniuToken, putExtra, config);
        console.log("observable" + observable)

        // 设置实例的监听对象
        var observer = {
          //上传过程的监听函数 result参数带有total字段的 object，包含loaded、total、percent三个属性)
          next(result) {
            // 实现上传进度条 ... 
            console.log(result)
          },
          //上传失败回调
          error(err) {
            console.log("失败", err.message)
          },
          // 上传完成回调
          complete(res) {
            // 提交数据给后端同事等业务逻辑 ....
            console.log("成功", res)
          }
        };
        var putExtra = {
          //原文件名
          fname: "",
          //用来放置自定义变量
          params: {},
          //限制上传文件类型 null || []
          mimeType: ["image/png", "image/jpeg","image/jpg", "image/gif"]
        };
        var config = {
          //存储区域(z0:代表华东;z2:代表华南,不写默认自动识别)
          region: qiniu.region.z2,
          //分片上传的并发请求量
          concurrentRequestLimit: 2
        };

        // console.log("qiniu"+qiniu.upload)
        // console.log("file"+file)
        // console.log("bucketToken"+bucketToken)
        // console.log("qiniuToken"+qiniuToken)
        // console.log("putExtra"+putExtra)
        // console.log("config"+config)

        // 上传开始
        var subscription = observable.subscribe(observer);
        // 取消上传
        // subscription.unsubscribe();
        console.log("end", subscription)

      },

      emitInput(fileList) {
        let value = [];
        for (let i = 0; i < fileList.length; i++) {
          value.push(fileList[i].url);
        }
        this.$emit("input", value);
      },
      handleRemove(file, fileList) {
        this.emitInput(fileList);
      },
      handlePreview(file) {
        this.dialogVisible = true;
        this.dialogImageUrl = file.url;
      },
      beforeUpload(file) {
        let _self = this;
        return new Promise((resolve, reject) => {
          policy()
            .then(response => {
              console.log("响应的数据", response);
              // _self.dataObj.policy = response.data.policy;
              // _self.dataObj.signature = response.data.signature;
              // _self.dataObj.ossaccessKeyId = response.data.accessid;
              // _self.dataObj.key = response.data.dir + getUUID() + '_${filename}';
              // _self.dataObj.dir = response.data.dir;
              // _self.dataObj.host = response.data.host;
              _self.dataObj.token = response.data.token;
              _self.dataObj.url = response.data.url;
              _self.dataObj.dirPrefix = response.data.dirPrefix;
              _self.dataObj.timePrefix = response.data.timePrefix;
              console.log("响应的数据222。。。", _self.dataObj);

              this.qiniuUp(file, _self);
              resolve(true)
              console.log("beforeUpload end");

            })
            .catch(err => {
              console.log("出错了...", err)
              reject(false);
            });
        });
      },
      handleUploadSuccess(res, file) {
        this.fileList.push({
          name: file.name, 
          url: this.url
        });
        this.emitInput(this.fileList);
      },
      handleExceed(files, fileList) {
        this.$message({
          message: "最多只能上传" + this.maxCount + "张图片",
          type: "warning",
          duration: 1000
        });
      }
    }
  };
</script>
<style>
</style>